# 记一次vue路由改造

# 原本

看看之前的路由

image.png

所有页面的路由全都注册在list中,数了下大概有800个页面了,太过冗余,下面开始动手改造吧

# 改造

建立modules文件夹

新建index.js,自动将目录下的所有文件引入

利用webpack的功能读取出所有文件

/**
 * 自动化处理文件:自动引入路由的核心文件
 */
const files = require.context('.', true, /\.js$/)

let configRouters = []
/**
 * inject routers
 */
files.keys().forEach(key => {
  if (key === './index.js') return
  configRouters = configRouters.concat(files(key).default) // 读取出文件中的default模块
})
export default configRouters

下面举个路由例子

/**
 * 球场路由
 */
export default [
  {
    pathname: 'BatchChangeCourtStatus',
    component: () => import('@/pages/court/BatchChangeCourtStatus')    // 球场批量订场
  }, {
    pathname: 'CourtSquare',
    title: '球场列表',
    component: () => import('@/components/base/CourtSquare')    // 球场广场列表
  }
]

导出个default数组,跟index中对应起来,不然读不到

再在总的路由index中引入modules中的index.js

import RouterModule from './modules'

通过结构到路由列表中
...RouterModule

至此,路由分层已做好了

# 拓展

之前的路由只有个keepalive功能,下面来进行拓展一下

const routerList = list.map(item => {
  return {
    path: '/' + item.pathname,
    name: item.pathname,
    meta: {
      keepAlive: item.keepAlive || false,
      title: item.title,
      hideTopBar: item.hideTopBar,
      requireLogin: item.requireLogin
    },
    component: item.component,
    children: item.children
  }
})

增加页面标题、隐藏项目头部引导、权限判断、隐藏微信分享功能

这里就要用到路由钩子了

router.beforeEach((to, from, next) => {
  hideWxShare()
  // 路由发生变化修改页面title
  if (to.meta.title) {
    document.title = to.meta.title
  }
  // 设置头部
  store.commit('setTopBar', !to.meta.hideTopBar)
  // 检查登录
  const haveUid = checkUid()
  if (to.meta.requireLogin) {
    if (haveUid) {
      next()
    } else {
      next({
        path: '/Login',
        query: { redirect: to.fullPath }
      })
      return
    }
  } else {
    next()
  }
})

# 隐藏微信分享功能

贴上代码

/**
 * 页面未加载完成时隐藏微信分享
 */
const hideWxShare = () => {
  if (_this.isWx) {
    let hrefString = location.href
    let data = {
      method: 'common_common_getSignPackage',
      url: hrefString
    }
    const Wx = window.jWeixin
    _this.$axios.post('baseApiEntry', data).then(res => {
      Wx.config({
        // debug: true,
        appId: res.appId,
        nonceStr: res.nonceStr,
        timestamp: res.timestamp,
        signature: res.signature,
        jsApiList: ['hideMenuItems']
      })
      Wx.ready(() => {
        Wx.hideMenuItems({
          menuList: [
            'menuItem:share:appMessage',
            'menuItem:share:timeline',
            'menuItem:share:qq',
            'menuItem:share:weiboApp',
            'menuItem:share:favorite',
            'menuItem:share:facebook',
            'menuItem:share:QZone'
          ]
        })
      })
    })
  }
}

思路就是每次进页面都跟够短请求获得appid等数据,然后在微信js桥ready情况下隐藏分享按钮

在需要的页面配置分享,同时打开分享按钮即可

# title

页面title及隐藏头部链接简单,判断有没值,有值改变即可

# 登录判断

如果有uid则是登录了,直接next()

没有就跳登录页面,在登录页面监听登录事件,登录成功则重定向到传入的to.fullPath页面

# 一个小坑

这里项目有一个坑,之前路由跳转是自己封装好的,在浏览器环境用的是location.href

导致路由守卫受到影响,会触发两次页面跳转,改成vue路由跳转方式后就好了